<template>
  <div class="page-container">
    <el-card shadow="never">
      <!-- 搜索 + 新增按钮 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
        <el-form :inline="true" :model="{ username: searchUsername }" @submit.prevent="handleSearch">
          <el-form-item label="用户名">
            <el-input v-model="searchUsername" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 新增用户按钮 -->
        <el-button type="primary" @click="addUser">新增用户</el-button>
      </div>

      <!-- 用户表格 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column align="center" prop="username" label="用户名"/>
        <el-table-column align="center" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === '0'" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createdAt" label="创建时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="resetPassword(row.id)">重置密码</el-button>
            <el-button
                size="small"
                :type="row.status === '0' ? 'danger' : 'success'"
                @click="toggleStatus(row)"
            >
              {{ row.status === '0' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="showAddDialog" title="新增用户" width="500px">
      <el-form :model="newUserForm" :rules="rules" ref="addUserFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUserForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUserForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import request from '@/api/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { nextTick } from 'vue';

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 搜索字段
const searchUsername = ref('');

// 新增用户相关
const showAddDialog = ref(false);
const newUserForm = reactive({
  username: '',
  email: ''
});
const addUserFormRef = ref(null); // 表单引用

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含中文、字母、数字、下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

// 获取用户列表
const fetchData = () => {
  loading.value = true;
  request.get('/api/user/list', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchUsername.value || undefined
    }
  })
      .then(res => {
        const data = res.data.data;
        tableData.value = data.records;
        total.value = data.total;
      })
      .catch(() => {
        tableData.value = [];
        total.value = 0;
      })
      .finally(() => {
        loading.value = false;
      });
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchUsername.value = '';
  handleSearch();
};

// 打开新增弹窗
const addUser = () => {
  showAddDialog.value = true;
  // 清空表单
  newUserForm.username = '';
  newUserForm.email = '';
  // 下次更新时重置校验（异步）
  nextTick(() => {
    if (addUserFormRef.value) {
      addUserFormRef.value.resetFields();
    }
  });
};

// 取消新增
const cancelAdd = () => {
  showAddDialog.value = false;
};

// 提交新增
const submitAdd = () => {
  addUserFormRef.value.validate(async valid => {
    if (!valid) return;

    try {
      const res = await request.post('/api/user/add', newUserForm);
      if (res.data.code === 200) {
        ElMessage.success('新增用户成功');
        showAddDialog.value = false;
        fetchData(); // 刷新列表
      }
    } catch (error) {
      console.error('新增失败:', error);
    }
  });
};

// 重置密码
const resetPassword = async (id) => {
  try {
    await ElMessageBox.confirm('确定要将该用户的密码重置吗？', '提示', {
      type: 'warning'
    });
    const res = await request.put(`/api/user/reset-password/${id}`);
    if (res.data.code === 200) {
      ElMessage.success('密码已重置');
    }
  } catch (error) {
    // 取消或请求失败
  }
};

// 启用/禁用用户
const toggleStatus = async (row) => {
  const isEnable = row.status === '1';
  const action = isEnable ? '启用' : '禁用';
  const api = isEnable ? `/api/user/enable/${row.id}` : `/api/user/disable/${row.id}`;

  try {
    await ElMessageBox.confirm(`确定要${action}该用户吗？`, '提示', {
      type: 'warning'
    });
    const res = await request.put(api);
    if (res.data.code === 200) {
      ElMessage.success(`${action}成功`);
      fetchData(); // 刷新
    }
  } catch (error) {
    // 失败或取消
  }
};

// 组件挂载后加载数据
onMounted(() => {
  fetchData();
});

// 时间格式化
const formatDate = (isoStr) => {
  return new Date(isoStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
